﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Toulr.Util
{
    public class HackHelper
    {
        /// <summary>
        /// 将用户输入的内容编码后输出到HTML页面，防止HTML注入和Js注入
        /// </summary>
        /// <param name="NoteContent">Content of the note.</param>
        /// <returns></returns>
        public string EncodeHtml(string content)
        {
            return content.Replace("<", "&lt").Replace(">", "&gt");
        }

        /// <summary>
        /// 防止SQL注入
        /// </summary>
        /// <param name="inputStr">输入的sql语句</param>
        /// <returns>过滤后的语句</returns>
        public static string NoSqlHack(string inputStr)
        {
            //要过滤掉的关键字集合
            string NoSqlHack_AllStr = "|;|and|chr(|exec|insert|select|delete|from|update|mid(|master.|";
            string SqlHackGet = inputStr;
            string[] AllStr = NoSqlHack_AllStr.Split('|');

            //分离关键字
            string[] GetStr = SqlHackGet.Split(' ');
            if (SqlHackGet != "")
            {
                for (int j = 0; j < GetStr.Length; j++)
                {
                    for (int i = 0; i < AllStr.Length; i++)
                    {
                        if (GetStr[j].ToLower() == AllStr[i].ToLower())
                        {
                            GetStr[j] = "";
                            break;
                        }
                    }
                }
                SqlHackGet = "";
                for (int i = 0; i < GetStr.Length; i++)
                {
                    SqlHackGet += GetStr[i].ToString() + " ";
                }
                return SqlHackGet.TrimEnd(' ').Replace("'", "_").Replace(",", "_").Replace("<", "&lt").Replace(">", "&gt");
            }
            else
            {
                return "";
            }
        }
    }
}
